<template>
  <div>
    <teacher-menu />
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <h2 class="text-2xl font-bold mb-4">发布试卷</h2>
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入试卷标题" />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
              type="textarea"
              v-model="form.description"
              placeholder="简要描述"
          />
        </el-form-item>

        <el-form-item label="题目列表">

          <div
              v-for="(q, index) in form.questions"
              :key="index"
              class="mt-4"
          >
            <el-card>
              <template #header>
                <span>题目 {{ index + 1 }}</span>
                <el-button
                    type="text"
                    @click="removeQuestion(index)"
                    style="float: right"
                >删除</el-button
                >
              </template>

              <el-input
                  v-model="q.title"
                  placeholder="请输入题干"
                  class="mb-2"
              />

              <el-select v-model="q.type" placeholder="请选择题型" class="mb-4">
                <el-option label="单选" value="single" />
                <el-option label="多选" value="multiple" />
                <el-option label="文本回答" value="text" />
              </el-select>

              <div v-if="q.type !== 'text'">
                <div
                    v-for="(opt, i) in q.options"
                    :key="i"
                    class="flex items-center mb-2"
                >
                  <el-input
                      v-model="opt.content"
                      placeholder="选项内容"
                      class="flex-1 mr-2"
                  />
                  <el-button
                      icon="el-icon-minus"
                      @click="q.options.splice(i, 1)"
                      type="danger"
                      circle
                  />
                </div>
                <el-button type="text" @click="q.options.push({ content: '' })"
                >添加选项</el-button
                >
              </div>
            </el-card>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-plus"  @click="addQuestion">添加题目</el-button>
          <el-button type="success" size="mini"  icon="el-icon-view" @click="submit">发布问卷</el-button>
        </el-form-item>
      </el-form>

      <el-dialog
          title="问卷预览"
          :visible.sync="previewVisible"
          width="60%"
      >
        <h3 class="text-xl font-semibold mb-2">{{ form.title }}</h3>
        <p class="mb-4">{{ form.description }}</p>
        <div
            v-for="(q, index) in form.questions"
            :key="index"
            class="mb-4"
        >
          <p><strong>{{ index + 1 }}. {{ q.title }}</strong></p>
          <ul v-if="q.type !== 'text'" class="list-disc list-inside">
            <li v-for="(opt, i) in q.options" :key="i">
              {{ opt.content }}
            </li>
          </ul>
          <p v-else>【文本题】</p>
        </div>
        <template #footer>
          <el-button @click="previewVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script>
import TeacherMenu from '@/components/teacher/Teacher_menu.vue';
import axios from 'axios';
import {EventBus} from "@/event-bus";

export default {
  name: 'PublishExam',
  components: { TeacherMenu },
  data() {
    return {
      // 用户信息
      UserInfo: {
        id: '',
        name: '',
        role: '',
        username: '',
      },
      form: {
        title: '',
        description: '',
        questions: []
      },
      previewVisible: false
    };
  },
  mounted() {
    this.getLoginUserInfo();
  },
  methods: {
    addQuestion() {
      this.form.questions.push({
        title: '',
        type: 'single',
        options: [{ content: '' }, { content: '' }]
      });
    },
    getLoginUserInfo() {
      axios.get('/user/checkSession').then(response => {
        if (!response.data.result) {
          EventBus.$emit('show-auth-popup');
          setTimeout(() => {
            this.$router.push({name: 'TeacherLoginView'});
          }, 1000);
        } else {
          this.UserInfo.name = response.data.name;
          this.UserInfo.role = response.data.role;
          this.UserInfo.username = response.data.username;
        }
      }).catch(error => {
        EventBus.$emit('show-auth-popup');
        console.error('获取用户信息失败,网络错误！', error);
        setTimeout(() => {
          this.$router.push({name: 'Login'});
        }, 1000);
      });
    },
    removeQuestion(index) {
      this.form.questions.splice(index, 1);
    },
    async submit() {
      if (!this.form.title.trim()) {
        this.$message.warning('请填写试卷标题');
        return;
      }
      if (this.form.questions.length === 0) {
        this.$message.warning('请至少添加一个题目');
        return;
      }

      let payloac=new FormData();
      payloac.append('title', this.form.title);
      payloac.append('description', this.form.description);
      payloac.append('questions', JSON.stringify(this.form.questions));
      payloac.append('fbz', this.UserInfo.username);
      payloac.append('fbzsfdm', 2);

      try {
        const res = await axios.post('/dcwjk/addDcwjk', payloac);
        this.$message.success('问卷已发布！');
        this.previewVisible = true;
      } catch (err) {
        this.$message.error('发布失败，请稍后重试');
        console.error(err);
      }
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style>
